import React from 'react';
import { Card, Form, Input, Button, Upload, message, Space, Divider, Row, Col } from 'antd';
import { UserOutlined, MailOutlined, PhoneOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import { useUserStore } from '@/store/user';
import { authApi } from '@/api/auth';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { UploadProps } from 'antd';

const { TextArea } = Input;

const ProfilePage: React.FC = () => {
  const { user } = useUserStore();
  const queryClient = useQueryClient();
  const [form] = Form.useForm();

  // 获取用户详情
  const { data: profile, isLoading, error } = useQuery({
    queryKey: ['userProfile'],
    queryFn: async () => {
      const response = await authApi.getUserProfile();
      return response;
    },
    enabled: !!user,
  });

  // 调试信息已清理

  // 更新用户资料
  const updateProfileMutation = useMutation({
    mutationFn: authApi.updateProfile,
    onSuccess: () => {
      message.success('个人资料更新成功！');
      queryClient.invalidateQueries({ queryKey: ['userProfile'] });
      queryClient.invalidateQueries({ queryKey: ['userDetails'] });
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  // 上传头像
  const uploadAvatarMutation = useMutation({
    mutationFn: authApi.uploadAvatar,
    onSuccess: () => {
      message.success('头像上传成功！');
      queryClient.invalidateQueries({ queryKey: ['userProfile'] });
      queryClient.invalidateQueries({ queryKey: ['userDetails'] });
    },
    onError: () => {
      message.error('头像上传失败，请重试');
    },
  });

  // 头像上传配置
  const uploadProps: UploadProps = {
    name: 'avatar',
    maxCount: 1,
    showUploadList: false,
    beforeUpload: (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG 格式的图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB！');
      }
      return isJpgOrPng && isLt2M;
    },
    customRequest: async ({ file, onSuccess, onError }) => {
      try {
        await uploadAvatarMutation.mutateAsync(file as File);
        onSuccess?.('ok');
      } catch (error) {
        onError?.(error as Error);
      }
    },
  };

  // 表单提交
  const handleSubmit = async (values: {
    username: string;
    email: string;
    name: string;
    mobile?: string;
    department?: string;
    position?: string;
    bio?: string;
    location?: string;
    website?: string;
  }) => {
    try {
      await updateProfileMutation.mutateAsync(values);
    } catch (error) {
      // 更新失败
    }
  };

  // 表单重置
  const handleReset = () => {
    form.resetFields();
  };

  React.useEffect(() => {
    if (profile) {
      form.setFieldsValue({
        username: profile.username,
        email: profile.email,
        name: profile.name,
        mobile: profile.mobile,
        department: profile.department,
        position: profile.position,
        bio: profile.bio,
        location: profile.location,
        website: profile.website,
      });
    }
  }, [profile, form]);

  return (
    <div style={{ height: '100%', width: '100%' }}>
      <Card title="个人资料" loading={isLoading} style={{ height: '100%' }}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          autoComplete="off"
        >
          <Row gutter={24}>
            <Col xs={24} sm={24} md={8} lg={6}>
              <div style={{ textAlign: 'center', marginBottom: 24 }}>
                <Upload {...uploadProps}>
                  <div style={{
                    width: 120,
                    height: 120,
                    borderRadius: '50%',
                    border: '2px dashed #d9d9d9',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    margin: '0 auto 16px',
                    overflow: 'hidden',
                    backgroundColor: '#fafafa',
                  }}>
                    {profile?.avatar ? (
                      <img
                        src={profile.avatar}
                        alt="avatar"
                        style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                      />
                    ) : (
                      <UserOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                    )}
                  </div>
                </Upload>
                <div style={{ marginTop: 8 }}>
                  <Button type="link" icon={<EditOutlined />}>
                    更换头像
                  </Button>
                </div>
              </div>
            </Col>
            <Col xs={24} sm={24} md={16} lg={18}>
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                  >
                    <Input
                      prefix={<UserOutlined />}
                      placeholder="请输入用户名"
                      disabled={true}
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名' }]}
                  >
                    <Input prefix={<UserOutlined />} placeholder="请输入姓名" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input prefix={<MailOutlined />} placeholder="请输入邮箱" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="手机号"
                    name="mobile"
                    rules={[
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }
                    ]}
                  >
                    <Input prefix={<PhoneOutlined />} placeholder="请输入手机号" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="部门"
                    name="department"
                  >
                    <Input placeholder="请输入部门" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="职位"
                    name="position"
                  >
                    <Input placeholder="请输入职位" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="所在地"
                    name="location"
                  >
                    <Input placeholder="请输入所在地" />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="个人网站"
                    name="website"
                  >
                    <Input placeholder="请输入个人网站" />
                  </Form.Item>
                </Col>
                <Col xs={24}>
                  <Form.Item
                    label="个人简介"
                    name="bio"
                  >
                    <TextArea
                      rows={4}
                      placeholder="请输入个人简介"
                      maxLength={200}
                      showCount
                    />
                  </Form.Item>
                </Col>
              </Row>
              <Divider />
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SaveOutlined />}
                    loading={updateProfileMutation.isPending}
                  >
                    保存修改
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
  );
};

export default ProfilePage;